/*
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
*/

#ifndef OH_WEB_RTC_OHOS_DESKTOP_H
#define OH_WEB_RTC_OHOS_DESKTOP_H

#include <mutex>
#include <memory>

#include <multimedia/player_framework/native_avscreen_capture.h>
#include <multimedia/player_framework/native_avscreen_capture_base.h>
#include <native_image/native_image.h>

#include "egl_render_context.h"


namespace webrtc {
namespace ohos {

class OhosDesktop {
public:
    int32_t Start();
    int32_t Stop();

    OH_NativeImage* GetNativeImage() { return nativeImage_; }
    static int32_t GetIsRunning() {
        return isRunning_.load();
    }
    static float *GetMatrix_() { return matrix_; }

    OhosDesktop(int32_t width = 1216, int32_t height = 2668): width_(width), height_(height) {};
    ~OhosDesktop();

private:
    int32_t width_ {2160};
    int32_t height_ {1440};
    int32_t Create();
    int32_t Config();
    int32_t Release();

    // 录屏回调: surface模式时OnBufferAvailable不触发
    static void OnError(OH_AVScreenCapture *capture, int32_t errorCode, void *userData);
    static void OnStateChange(struct OH_AVScreenCapture *capture, OH_AVScreenCaptureStateCode stateCode, void *userData);
    static void OnBufferAvailable(OH_AVScreenCapture *capture, OH_AVBuffer *buffer, OH_AVScreenCaptureBufferType bufferType,
                                  int64_t timestamp, void *userData);
    int32_t SetStateCode(OH_AVScreenCaptureStateCode stateCode);

    // RenderContext(EglContext EglDisplay)创建和销毁
    bool InitRenderContext();
    int32_t DestroyRenderContext();
    std::unique_ptr<EglRenderContext> renderContext_ {nullptr};

    // NativeWindow创建和销毁
    bool CreateNativeWindow();
    int32_t DestroyNativeWindow();
    OHNativeWindow *nativeWindow_ {nullptr};

    // NativeImage回调函数
    static void OnNativeImageFrameAvailable(void *data);
    int32_t FrameAvailable();
    OH_OnFrameAvailableListener nativeImageFrameAvailableListener_{};

    // NativeImage创建和销毁，需要使用eglSurface,textureID
    bool CreateNativeImage();
    int32_t DestroyNativeImage();
    OH_NativeImage *nativeImage_ {nullptr};
    GLuint nativeImageTextureID_ {0U};
    EGLSurface eglSurface_ {EGL_NO_SURFACE};

    OH_AVScreenCapture *capture_ {nullptr};
    OH_AVScreenCaptureStateCode stateCode_ {OH_SCREEN_CAPTURE_STATE_STOPPED_BY_USER};
    static std::atomic<bool> isRunning_;
    static float matrix_[16];
};

} // namespace ohos
} // namespace webrtc
#endif //OH_WEB_RTC_OHOS_DESKTOP_H
